﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;

namespace RantopadService.Business
{
    public class XMLHelper
    {
        public static DataSet decodeMacroXmltoDS(string xmlStr)
        {
            DataSet ds = new DataSet();
            xmlStr = xmlStr.Replace("<rtmacro", "#<rtmacro");
            xmlStr = xmlStr.Replace("</macro>", "#</macro>");
            string[] xmlstrs = xmlStr.Split('#');
            for (int i = 1; i < xmlstrs.Length - 1; i++)
            {
                ds.Tables.Add(decodeMacroXmltoDT(xmlstrs[i]));
            }
            
            return ds;
        }
        public static DataTable decodeMacroXmltoDT(string xmlStr)
        {            
            DataTable macroTable = new DataTable();
            DataColumn c1 = new DataColumn("type", System.Type.GetType("System.String"));
            DataColumn c2 = new DataColumn("time", System.Type.GetType("System.Decimal"));
            DataColumn c3 = new DataColumn("keyid", System.Type.GetType("System.Int64"));
            DataColumn c4 = new DataColumn("action", System.Type.GetType("System.String"));
            //DataColumn c5 = new DataColumn("keytype", System.Type.GetType("System.String"));
            macroTable.Columns.Add(c1);
            macroTable.Columns.Add(c2);
            macroTable.Columns.Add(c3);
            macroTable.Columns.Add(c4);
            //macroTable.Columns.Add(c5);
            using (StringReader strRdr = new StringReader(xmlStr))
            {
                using (XmlReader rdr = XmlReader.Create(strRdr))
                {
                    while (rdr.Read())
                    {
                        string elementName = rdr.Name;
                        if (elementName=="rtmacro")
                        {
                            macroTable.TableName = rdr["name"].ToString();
                            while (rdr.Read())
                            {
                                elementName = rdr.Name;
                                if (elementName == "item")
                                {
                                    DataRow newRow = macroTable.NewRow();
                                    newRow["type"] = rdr["type"].ToString();
                                    newRow["time"] = Convert.ToDecimal(rdr["time"]);
                                    newRow["keyid"] = Convert.ToInt64(rdr["keyid"]);
                                    newRow["action"] = rdr["action"].ToString();

                                    //newRow["keytype"] = rdr["keytype"].ToString();

                                    macroTable.Rows.Add(newRow);
                                }
                            }
                            
                        }
                        
                    }
                }
            }

            return macroTable;
        }
    }
}